#include <rtthread.h>
#include <board.h>
#include <rthw.h>
#include "rtdevice.h"
#include "nuc970_gpio.h"

/* defined the LED0 pin: PH4 */
/* defined the LED1 pin: PH5 */
//#define LED0_PIN    GET_PIN(B, 1)     // APOLLO
//#define LED1_PIN    GET_PIN(B, 0)
//#define LED0_PIN    GET_PIN(A, 5)
//#define LED1_PIN    GET_PIN(A, 6)
//#define LED0_PIN    GET_PIN(H, 4)     // 3113
//#define LED1_PIN    GET_PIN(H, 5)
#define LED0_PIN    GET_PIN(D, 3)     // 1M55
#define LED1_PIN    GET_PIN(D, 4)
#define GPIO_PIN    GET_PIN(D, 5)

rt_thread_t led_tid = RT_NULL;
rt_timer_t led1_timer;

//rt_timer_t th_timer;
//static struct rt_completion th_comp;
//rt_sem_t led_sem;

static void led1_timeout(void *parameter)
{
    static int pin = 1;//rt_pin_read(LED1_PIN); 
    pin = !pin;
    rt_pin_write(LED1_PIN, pin);
//    rt_sem_release(led_sem);
}

//static void th_timeout(void *parameter)
//{
//    rt_completion_done(&th_comp);
//}

static void pin_irq_callback(void *args)
{
    rt_uint32_t reg;

    rt_kprintf("%s\n", args);
    reg = GPIOD->ISR;
    if (reg & BIT5) {
        // do your op here
        
        GPIO_ClrISRBit(GPIOD, BIT5);
    } else {
        // other bits op here
    }
}

void led_tick_thread(void *parameter)
{
    int pin = 1, i;

    led1_timer = rt_timer_create("ledtim", led1_timeout,
                                RT_NULL,  1000,
                                RT_TIMER_FLAG_PERIODIC | RT_TIMER_FLAG_SOFT_TIMER);
    if (led1_timer != RT_NULL) {
        rt_timer_start(led1_timer);
    }
//    th_timer = rt_timer_create("thtim", th_timeout,
//                                RT_NULL,  500,
//                                RT_TIMER_FLAG_ONE_SHOT | RT_TIMER_FLAG_SOFT_TIMER);

//    led_sem = rt_sem_create("ledsem", 1, RT_IPC_FLAG_PRIO);
    while (1) {
        rt_pin_write(LED0_PIN, PIN_HIGH);
        rt_thread_mdelay(500);
        rt_pin_write(LED0_PIN, PIN_LOW);
        rt_thread_mdelay(500);
//        rt_completion_init(&th_comp);
//        rt_timer_start(th_timer);
//        rt_completion_wait(&th_comp, 1000);
//        rt_sem_take(led_sem, 3000);
//        pin = rt_pin_read(GPIO_PIN);
//        rt_kprintf("GPIO_PIN: %d\n", pin);
    }
}

int led_tick_init(void)
{
    /* set LED0 LED1 pin mode to output */
    rt_pin_mode(LED0_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(LED1_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(GPIO_PIN, PIN_MODE_INPUT);

    rt_pin_attach_irq(GPIO_PIN, PIN_IRQ_MODE_FALLING, pin_irq_callback, "pin irq");

    rt_pin_irq_enable(GPIO_PIN, PIN_IRQ_ENABLE);

    led_tid = rt_thread_create("ledtick",              
                           led_tick_thread, RT_NULL,
                           1024,
                           RT_THREAD_PRIORITY_MAX - 2,
                           2);
    if (led_tid != RT_NULL)
        rt_thread_startup(led_tid);
    return 0;
}
INIT_APP_EXPORT(led_tick_init);
